package edu.scau.ojforwarder.service;

import edu.scau.ojforwarder.bean.NowcoderError;
import edu.scau.ojforwarder.bean.NowcoderSubmission;
import edu.scau.ojforwarder.bean.BaseResult;
import edu.scau.ojforwarder.bean.NowcoderStatus;
import edu.scau.ojforwarder.util.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class NowcoderService {

    @Autowired
    private NowcoderClient nowcoderClient;

    @Autowired
    private NowcoderSubmitTask submitTask;

    @Autowired
    private NowcoderStatusManager statusManager;

    public BaseResult<NowcoderStatus> addSubmission(NowcoderSubmission submission) {
        String submissionId = submitTask.addSubmission(submission);
        NowcoderStatus status = statusManager.getStatus(submissionId);
        return ResultGenerator.genResult(NowcoderError.SUCCESS, status);
    }

    public BaseResult<NowcoderStatus> getStatus(String submissionId) {
        NowcoderStatus status = statusManager.getStatus(submissionId);
        if (status == null)
            return ResultGenerator.genResult(NowcoderError.NO_SUCH_SUBMISSION);
        if (status.getStatus().equals(NowcoderStatus.QUEUING)) {
            statusManager.updateStatus(submissionId);
            status = statusManager.getStatus(submissionId);
        }
        if (status.getError() != null)
            return ResultGenerator.genResult(status.getError(), status);
        else
            return ResultGenerator.genResult(NowcoderError.SUCCESS, status);
    }

    public BaseResult<String> getProblemDesc(String contestId, String problemNum) {
        try {
            String problemDesc = nowcoderClient.getProblemInfo(contestId, problemNum).getDescription();
            return ResultGenerator.genResult(NowcoderError.SUCCESS, problemDesc);
        } catch (ErrorException e) {
            return ResultGenerator.genResult(e.getError());
        }
    }
}
